﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Linq;
using IphoneTrackerDotNet.Properties;
using mbdbdump;

namespace IphoneTrackerDotNet
{
    public partial class Form1 : Form
    {

        private readonly List<iPhoneBackup> _backups = new List<iPhoneBackup>();
        private List<Localizacao> _listaLocal = new List<Localizacao>();
        private  List<mbdbdump.mbdb.MBFileRecord> m_DbFiles = new List<mbdb.MBFileRecord>();
        private mbdb.MBFileRecord[] _files92;

        
        

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1Load(object sender, EventArgs e)
        {

         
            LoadManifests();         

        }
        private void ShowImBrowser()
        {
            const string filename = "index.htm";
            string dsTodoArquivo;
            using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                using (TextReader reader = new StreamReader(fs, Encoding.UTF8))
                {
                    dsTodoArquivo = reader.ReadToEnd();
                }
            }
            string dsJs = IphoneCellLocationDal.GetScriptCoordenators(_listaLocal);
            var backup = (iPhoneBackup)comboBox1.SelectedItem;
            dsTodoArquivo = dsTodoArquivo.Replace("g_csvString = null;", "g_csvString =\"" + dsJs + "\";");
            dsTodoArquivo = dsTodoArquivo.Replace("g_deviceName = null;", "g_deviceName = \"" + backup.DeviceName +"\";");
            string path = Path.GetTempPath() + Path.GetRandomFileName()+".htm";

            using (var outfile = new StreamWriter(path))
            {
                outfile.Write(dsTodoArquivo);
            }
            

            textBox1.Text = path;
            try
            {
                System.Diagnostics.Process.Start("firefox.exe", path);
            }
            catch 
            {
                try
                {
                    System.Diagnostics.Process.Start("chrome", path);
                }
                catch 
                {
                    System.Diagnostics.Process.Start("Iexplorer", path);
                }
                
            }
            
        }

        private void Button1Click(object sender, EventArgs e)
        {
            LoadManifests();
        }

        private void LoadManifests()
        {
            _backups.Clear();
            comboBox1.Items.Clear();
            //listView1.Items.Clear();
           

            string s = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

            s = Path.Combine(s, "Apple Computer");
            s = Path.Combine(s, "MobileSync");
            s = Path.Combine(s, "Backup");

            var d = new DirectoryInfo(s);

            foreach (DirectoryInfo sd in d.GetDirectories())
            {
                LoadManifest(sd.FullName);
            }

            foreach (iPhoneBackup b in _backups)
            {
                comboBox1.Items.Add(b);
            }

            //comboBox1.SelectedIndex = 0;
        }

        private void LoadManifest(string path)
        {
            string filename = Path.Combine(path, "Info.plist");

            try
            {
                xdict dd = xdict.open(filename);

                if (dd != null)
                {
                    var backup = new iPhoneBackup {path = path};

                    foreach (xdictpair p in dd)
                    {
                        if (p.item.GetType() == typeof(string))
                        {
                            switch (p.key)
                            {
                                case "Device Name": backup.DeviceName = (string)p.item; break;
                                case "Display Name": backup.DisplayName = (string)p.item; break;
                                case "Last Backup Date": backup.LastBackupDate = (string)p.item; break;
                            }
                        }
                    }

                    _backups.Add(backup);
                }
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show(ex.InnerException.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void ComboBox1SelectedIndexChanged(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;         
            
            
            _files92 = null;


            try
            {
                var backup = (iPhoneBackup)comboBox1.SelectedItem;

                // backup iTunes 9.2+
                if (File.Exists(Path.Combine(backup.path, "Manifest.mbdb")))
                {
                    _files92 = mbdb.ReadMBDB(backup.path, false, true);
                    var b = _files92.ToList();
                    m_DbFiles = b.Where(dbf => dbf.Path.Contains(".db")).OrderBy(g=>g.Path).ToList();

                    var dbFiles = m_DbFiles.Where(dbf => dbf.Path.Contains(".db")).Select(f => f.Path).Distinct().ToList();
                    listBox1.DataSource = dbFiles;
                    var enc = b.Where(c => c.Path.Contains("consolidated.db")).ToList();
                    if (enc.Count == 0)
                    {
                        MessageBox.Show(Resources.rs_dados_nao_localizados, Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                        return;

                    }

                    string ext = "";
                    if (_files92 == null)
                        ext = ".mddata";
                    string dsCaminho = Path.Combine(backup.path, enc[0].key + ext);
                    if (!File.Exists(dsCaminho))
                    {
                        MessageBox.Show(Resources.rs_dados_nao_localizados, Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                        return;

                    }
                    ListaCorrdenadas(dsCaminho);
                    label3.Text = backup.DeviceName;
                    label4.Text = backup.DisplayName;
                    label5.Text = backup.LastBackupDate;
                    label6.Text = backup.path;

                    return;
                }
            }
            catch (InvalidOperationException ex)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show(ex.InnerException.ToString());
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show(string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }

            Cursor.Current = Cursors.Default;
        }

        private void ListaCorrdenadas(string caminho)
        {
            var d = new IphoneCellLocationDal();

           _listaLocal = d.GetLocalizcao(caminho);
           if (_listaLocal.Count==0)
           {
               exportarToolStripMenuItem.Enabled = false;
               button2.Enabled = false;
               MessageBox.Show(Resources.Iphone_recem_formatado, Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
               return;

           }
            button2.Enabled = true;
            exportarToolStripMenuItem.Enabled = true;
           
           
        }

        private void JavaScriptToolStripMenuItemClick(object sender, EventArgs e)
        {
            var dr = saveFileDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                IphoneCellLocationDal.SaveJsTrackData(_listaLocal, saveFileDialog1.FileName);
            }
            
        }

        private void CVsToolStripMenuItemClick(object sender, EventArgs e)
        {
            var dr = saveFileDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                IphoneCellLocationDal.SaveCvsTrackData(_listaLocal, saveFileDialog1.FileName);
            }
        }

        private void KSmToolStripMenuItemClick(object sender, EventArgs e)
        {
            DialogResult dr = saveFileDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                IphoneCellLocationDal.SaveKsmTrackData(_listaLocal, saveFileDialog1.FileName);
            }
        }

        private void SairToolStripMenuItemClick(object sender, EventArgs e)
        {
            Close();
        }

        private void Button2Click(object sender, EventArgs e)
        {
            ShowImBrowser();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            iPhoneBackup backup = (iPhoneBackup)comboBox1.SelectedItem;
            string arquivo = listBox1.SelectedItem.ToString();

            var obArquivo = m_DbFiles.SingleOrDefault(p => p.Path == arquivo).key;
            textBox2.Text = Path.Combine(backup.path, obArquivo);
            //string argument = @"/select, """ + Path.Combine(backup.path, obArquivo) + @"""";

            //System.Diagnostics.Process.Start("explorer.exe", argument);
        }

    }
}
